<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016/12/23
 * Time: 10:43
 */
include_once "../vendor/autoload.php";

use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use QL\QueryList;

class GetFile
{
    private $base_url;

    private $inCharset;

    private $outCharset;

    private $client;

    public function __construct($base_url, $inCharset = '', $outCharset = '')
    {
        //
        $this->base_url = $base_url;
        $this->inCharset = $inCharset;
        $this->outCharset = $outCharset;
        $this->client = new Client();
    }

    public function getString($uri)
    {
        return $this->client->request('GET', $uri);
    }

    public function process()
    {
        //step1
        $uri = '';

        $step1 = $this->getString($this->base_url.$uri);

        $rs = $step1->getBody()->getContents();

//        $fileType = mb_detect_encoding($rs , array('UTF-8', 'GBK', 'LATIN1', 'BIG5', 'GB2312'));
//
//        if( $fileType !== 'UTF-8'){
//            $rs = mb_convert_encoding($rs ,'UTF-8' , $fileType);
//        }

        //regex
        $file = $this->regexFileUri($rs);

        if (!$file) {
            die("the file uri was not found!");
        }

        echo $this->getFile($file);
    }

    public function regexFileUri($contents)
    {
//        $rules = [
////            'logo'  =>  ['.logo>img', 'src'],
////            'title' =>  ['title', 'html'],
//            'h1'     =>  ['h1', 'text'],
//            'bt1'   =>  ['.bt-blue', 'href'],
//            'bt2'   =>  ['.bt-green', 'href']
//        ];
        $rules = [
            'articles'  =>  ['.title', 'href']
        ];
        $response = QueryList::Query($contents, $rules, '', $this->inCharset, $this->outCharset, false)->getData();

//        $fileType = mb_detect_encoding($response[0]['h1'] , array('UTF-8', 'GBK', 'LATIN1', 'BIG5', 'GB2312'));
//        var_dump($fileType);
//        if( $fileType !== 'UTF-8'){
////            $response[0]['h1'] = mb_convert_encoding($response[0]['h1'] ,'UTF-8' , $fileType);
//            $response[0]['h1'] = iconv($fileType, 'UTF-8', $response[0]['h1']);
//        }
//        header('Content-type:text/html;charset=');
        var_dump($response);die;
    }

    public function getFile()
    {

    }

}

$s = new GetFile('http://www.lanrenzhijia.com/nav/list_3_2.html', '', '');
$s->process();